package util

import (
	"crypto/aes"
	"encoding/base64"
	"fmt"
)

// AesEBC解密
func AesEBCDeCode(str string) (string, error) {
	if str == "" || str == " " {
		return "", nil
	}
	src, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return "", err
	}
	key := []byte("9871267812345mn812345xyz") // AES-128 requires a 16 bytes key
	plaintext, err := aesEBCDecrypt(src, key)
	if err != nil {
		// log.Fatalf("Decryption failed: %s", err)
		return "", err
	}
	return string(plaintext), nil
}
func aesEBCDecrypt(ciphertext, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	if len(ciphertext)%aes.BlockSize != 0 {
		return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
	}

	plaintext := make([]byte, len(ciphertext))
	for bs := 0; bs < len(ciphertext); bs += aes.BlockSize {
		block.Decrypt(plaintext[bs:bs+aes.BlockSize], ciphertext[bs:bs+aes.BlockSize])
	}

	// If PKCS7 padding was used, remove it.
	plaintext, err = pkcs7Unpad(plaintext, aes.BlockSize)
	if err != nil {
		return nil, err
	}
	return plaintext, nil
}

// pkcs7Unpad removes PKCS#7 padding from a byte slice.
func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
	if blockSize <= 0 {
		return nil, fmt.Errorf("blockSize must be greater than zero")
	}
	if len(data)%blockSize != 0 {
		return nil, fmt.Errorf("data length is not a multiple of blockSize")
	}
	padLen := int(data[len(data)-1])
	if padLen > blockSize || padLen == 0 {
		return nil, fmt.Errorf("invalid padding")
	}
	for i := 1; i <= padLen; i++ {
		if data[len(data)-i] != byte(padLen) {
			return nil, fmt.Errorf("invalid padding")
		}
	}
	return data[:len(data)-padLen], nil
}
